# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql


class BaiduPipeline(object):
    def __init__(self):
        # 连接MySQL数据库
        self.connect = pymysql.connect(host='localhost',
                                       user='root', password='Lj970914',
                                       db='douban', port=3306)  # db要和建的数据库名称对应上
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
        # 往数据库里面写入数据
        self.cursor.execute('delete from scrapy')
        for hot in item['hots']:
            # print(hot)
            self.cursor.execute('insert into scrapy(hot)VALUES ("{}")'.format(hot))# 表的名字要和建的表名对应
        # for name in item['names']:
        #     #     # self.cursor.execute('delete 热点人物 from scrapy')
        #     self.cursor.execute('insert into scrapy(name)VALUES ("{}")'.format(name))
        self.connect.commit()
        return item

    # 关闭数据库
    def close_spider(self, spider):
        self.cursor.close()
        self.connect.close()
